<?php

require 'tag/tag.php';

//解析模板中的变量与标签
class Compile extends Tag
{

	//模板内容
	protected $content;

	//解析类入口
	protected function compileTpl($content)
	{
		$this->content = $content;

		//解析变量
		$this->parseVars();

		//解析标签
		$this->parseTag();

		return $this->content;
	}

	//解析变量
	private function parseVars()
	{
		//{{$web}}   <?php echo $web;? >
		$pattern='/\{\{(.*?)\}\}/i';
		$replacement='<?php echo \1;?>';
		$this->content =  preg_replace($pattern, $replacement, $this->content);
	}

	//解析标签
	private function parseTag()
	{
		$obj = new Tag;
		//获取对象属性
		$tags = $obj->tag;
		foreach($tags as $tag=>$params)
		{
			if($params['block']==1)
			{
				//块标签的处理
				$preg = '/<'.$tag.'(.*?)>(.*?)<\/'.$tag.'>/is';

				if(preg_match_all($preg, $this->content, $matches,PREG_SET_ORDER))
				{
					foreach($matches as $t)
					{
					//标签属性
						$attr = $this->getTagAttr($t[1]);
					//标签内容
						$body = $t[2];
						$method= '_'.$tag;
						$replace = $obj->$method($attr,$body);
						$this->content = str_replace($t[0], $replace, $this->content);
					}
				}
			}
			else
			{
				//行标签的处理
				$preg = '/<'.$tag.'(.*?)\/>/is';
				if(preg_match_all($preg, $this->content, $matches,PREG_SET_ORDER))
				{
					foreach($matches as $t)
					{
					//标签属性
						$attr = $this->getTagAttr($t[1]);
						$method= '_'.$tag;
						$replace = $obj->$method($attr,'');
						$this->content = str_replace($t[0], $replace, $this->content);
					}
				}
			}
		}
	}

	//获取标签属性
	private function getTagAttr($str)
	{
		$attr=[];

		$preg = '/(\w+?)=[\'"](.+?)[\'"]/i';
		if(preg_match_all($preg, $str, $matches,PREG_SET_ORDER))
		{
			foreach($matches as $v)
			{
				$attr[$v[1]]=$v[2];
			}
		}
		return $attr;
	}
}













